<template>
  <el-dialog
    :close-on-click-modal="false"
    title="机械处调回明细"
    :visible.sync="show"
    width="1060px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="120px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="调拨单号" prop="allocNumber">
            <el-input v-model="form.allocNumber" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showDeviceConfigModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="申请编号" prop="deviceConfigPlanInfoApplyNumber">
            <el-input v-model="form.deviceConfigPlanInfoApplyNumber" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调拨时间" prop="allocTime">
            <el-date-picker v-model="form.allocTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调出单位名称" prop="recallUnitName">
            <!-- <el-select v-model="form.recallUnitName" :disabled="disableForm" style="width: 100%;" placeholder="请选择">
              <el-option label="公司机构" value="公司机构" />
              <el-option label="项目部" value="项目部" />
            </el-select> -->
            <el-input v-model="form.recallUnitName" :disabled="disableForm" />

          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调出单位责任人" prop="recallUnitHead">
            <el-input v-model="form.recallUnitHead" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调回单位名称" prop="transferUnitName">
            <el-input v-model="form.transferUnitName" :disabled="true" placeholder="机械处" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调入单位责任人" prop="transferUnitHead">
            <el-input v-model="form.transferUnitHead" :disabled="true" placeholder="机械处主任王斌" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4" :disabled="disableForm" />
      </el-form-item>

      <div style="padding-bottom: 10px;">
        <el-button type="primary" @click="showTargetSetListModal = true">引入设备</el-button>
        <el-button type="primary" @click="deleteDetail">删除设备</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:devNumber="{row}">
          <el-input v-model="row.devNumber" />
        </template>
        <template v-slot:devName="{row}">
          <el-input v-model="row.devName" />
        </template>
        <template v-slot:specification="{row}">
          <el-input v-model="row.specification" />
        </template>
        <template v-slot:payTime="{row:{payTime}}">
          {{ dateFormat(payTime) }}
        </template>
        <template v-slot:unit="{row}">
          <!-- <el-input v-model="row.unit" /> -->
          <el-select v-model="row.unit" :disabled="disableForm" style="width: 100%;" placeholder="请选择">
            <el-option label="台班" :value="1" />
            <el-option label="小时" :value="2" />
            <el-option label="月" :value="3" />
            <el-option label="吨" :value="4" />
            <el-option label="㎡" :value="5" />
            <el-option label="m³" :value="6" />
          </el-select>
        </template>
        <template v-slot:workload="{row}">
          <el-input v-model="row.workload" @input="sum()" />
        </template>
        <template v-slot:unitPrice="{row}">
          <el-input v-model="row.unitPrice" @input="sum()" />
        </template>
        <template v-slot:sumPrice="{row}">
          <el-input v-model="row.sumPrice" />
        </template>
        <template v-slot:useUnit="{row}">
          <el-input v-model="row.useUnit" />
        </template>
        <template v-slot:approachLocation="{row}">
          <el-input v-model="row.approachLocation" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
        <template v-slot:options="{row}">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRow(row)">删除</el-button>
        </template>

      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <!-- <deviceList title="易耗品台账列表" :show-modal.sync="showTargetSetListModal" :columns="columns" :api-obj="{api:getConsumableLedgerList}" @getSelectedRows="getSelectedRows" /> -->
    <deviceConfigList :show-modal.sync="showDeviceConfigModal" @getSelectedData="getSelectedData" />
    <tree-modal title="机械设备选择(多选)" :check-lock="false" :show-modal.sync="showTargetSetListModal" :columns="columns" :api-obj="{tree:getMachineDirectoryTree,list:getMachineDeviceDetailList}" @getSelectedRows="getSelectedRows" />
    <listSelect :show-modal.sync="showListModal" title="机械设备配置计划选择" :columns="listColumns" :api="getDeviceConfigPlanFinishInfoList" @getSelectedData="getSelectedConfigRows" />

  </el-dialog>

</template>

<script>
import { addDeviceInputInfo, updateDeviceInputInfo, getDeviceInputInfoDetail, getDeviceConfigPlanFinishInfoList } from '@/api/consumableManage'
import { getMachineDirectoryTree, getMachineDeviceDetailList } from '@/api/basicCode'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import moment from 'moment'
import listSelect from '@/components/ListSelect'
import { getConsumableLedgerList, getDeviceConfigPlanDetailList } from '@/api/consumableManage'

// import deviceList from './deviceList'
import treeModal from './machineSelect.vue'
import fileUploader from '@/components/FileUploader'
import deviceConfigList from './deviceConfigList.vue'
export default {
  name: 'AddDeviceAllocationInfo',
  components: {
    fileUploader,
    // deviceList,
    listSelect,
    treeModal,
    deviceConfigList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getDeviceConfigPlanDetailList,
      getDeviceConfigPlanFinishInfoList,
      showListModal: false,
      listColumns: [
        {
          label: '申请编号',
          prop: 'applyNumber'
        },
        {
          label: '申请时间',
          prop: 'applyTime',
          slot: 'applyTime',
          width: '90'
        },
        {
          label: '计划总金额',
          prop: 'amount'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '流程状态',
          prop: 'status',
          slot: 'status'
        },
        {
          label: '编制人',
          prop: 'founderName'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          slot: 'createTime',
          width: '90'
        }
      ],
      getConsumableLedgerList,
      getMachineDeviceDetailList,
      getMachineDirectoryTree,
      showDeviceConfigModal: false,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        // allocNumber: '',
        deviceConfigPlanInfoApplyNumber: '',
        deviceConfigPlanInfoId: '',
        allocTime: '',
        recallUnitName: '',
        recallUnitHead: '',
        transferUnitName: '机械处',
        transferUnitHead: '机械处主任王斌',
        remark: ''
      },
      columns: [
        {
          label: '设备编号',
          prop: 'devNumber'
        },
        {
          label: '设备名称',
          prop: 'devName',
          width: '180'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        // {
        //   label: '购入时间',
        //   prop: 'payTime',
        //   slot: 'payTime',
        //   width: '90'
        // },
        {
          label: '单位',
          slot: 'unit',
          width: '120'
        },
        {
          label: '实际工作量',
          slot: 'workload',
          width: '100'
        },
        {
          label: '单价',
          slot: 'unitPrice',
          width: '150'
        },
        {
          label: '合价',
          slot: 'sumPrice',
          width: '150'
        },
        {
          label: '使用单位',
          slot: 'useUnit',
          width: '150'
        },
        {
          label: '进场地点',
          slot: 'approachLocation',
          width: '150'
        },
        {
          label: '备注',
          slot: 'remark',
          width: '150'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '140',
          prop: 'options',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        allocNumber: [
          { required: true, message: '请选择调拨单号', trigger: 'change' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请选择备注', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    // data: {
    //   handler(newData, oldData) {
    //     if (newData.id) {
    //       this.getDocDetail(newData.id)
    //       Object.keys(this.form).forEach(key => {
    //         const source = newData[key]
    //         if (typeof source === 'boolean') {
    //           this.form[key] = source ? 1 : 0
    //         } else {
    //           this.form[key] = source
    //         }
    //       })
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    // },
    showModal(val) {
      if (val) {
        if (this.optType !== 'add') {
          this.getDocDetail(this.data.id)
          this.$nextTick(() => {
            Object.keys(this.form).forEach(key => {
              const source = this.data[key]
              if (typeof source === 'boolean') {
                this.form[key] = source ? 1 : 0
              } else {
                this.form[key] = source
              }
            })
          })
        } else if (this.optType === 'add') {
          this.form.transferUnitName = '机械处'
          this.form.transferUnitHead = '机械处主任王斌'
        }
      } else if (!val) {
        this.targetList = []
        this.fileList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    const json = JSON.parse(localStorage.getItem('USER_INFO'))
    this.form.recallUnitHead = json.name
    this.form.recallUnitName = json.organizationName
    this.getRegionData()
  },
  methods: {
    sum(row) {
      this.targetList.forEach(item => {
        if (item.workload && item.unitPrice) {
          item.sumPrice = item.workload * item.unitPrice
        } else {
          item.sumPrice = ''
        }
      })
    },
    getSelectedConfigRows(data) {
      getDeviceConfigPlanDetailList({ deviceConfigPlanInfoId: data.id }).then(res => {
        const list = res.data
        list.forEach(element => {
          this.targetList.push({
            ...element,
            devName: element.name,
            devNumber: element.number
          })
        })
      })
      if (data) {
        // this.supplierInfo = data
        const { applyNumber, id } = data
        this.form.deviceConfigPlanInfoId = id
        this.form.deviceConfigPlanInfoApplyNumber = applyNumber
      }
    },
    getSelectedData(data) {
      if (data) {
        this.form.allocNumber = data.applyNumber
      }
    },
    delRow(data) {
      this.$confirm('确定要删除该数据吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.targetList.indexOf(data)
        if (index > -1) {
          this.targetList.splice(index, 1)
        }
      }).catch(() => {
      })
    },
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSelectedRows(data) {
      this.targetList = this.targetList.concat(data.map(item => {
        delete item.id
        return {
          ...item
        }
      }))
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getDeviceInputInfoDetail({ deviceInputInfoId: id }).then(res => {
        const { lstAttachment, lstDeviceInputDetail } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstDeviceInputDetail && lstDeviceInputDetail.length > 0) {
          this.targetList = lstDeviceInputDetail
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.targetList.map(item => {
          //   item.id = ''
          // })
          const params = {
            deviceInputInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstAttachment: this.fileList,
            lstDeviceInputDetail: this.targetList.map(item => {
              return {
                ...item,
                id: null,
                ...this.optType === 'edit' ? {
                  deviceInputInfoId: this.data.id
                } : {}
              }
            })
          }
          const fn = this.optType === 'add' ? addDeviceInputInfo : updateDeviceInputInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
